<template>
  <div id="app">
    <!-- 导航栏  -->
    <NavbarComponent></NavbarComponent>

    <!-- 主页头部 -->
    <header class="header">
      <div class="category-sidebar">
        <div 
          class="category-item"
          v-for="item in sidebarCategories"
          :key="item.name"
          @click="handleCategoryClick(item.category)"
        >
          {{ item.name }}
          <el-icon><component :is="item.icon" /></el-icon>
        </div>
      </div>
      <div class="main-content">
      <div class="carousel-container">
        <el-carousel 
          indicator-position="outside"
          height="400px"
          :interval="5000"
          arrow="always"
        >
          <el-carousel-item v-for="(item, index) in bannerImages" :key="index" @click.native="handleBannerClick(item)">
            <div class="carousel-item">
              <img 
                :src="item.image" 
                :alt="'Banner ' + (index + 1)"
                class="carousel-image"
              >
              <div class="carousel-caption">
                <h2>{{ item.title }}</h2>
                <p>{{ item.description }}</p>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
      <el-card class="notice-board">
  <!-- 顶部标签页 -->
  <div class="notice-tabs">
    <div 
      v-for="tab in noticeTabs"
      :key="tab.type"
      class="tab-item"
      :class="{ active: activeNoticeType === tab.type }"
      @click="activeNoticeType = tab.type"
    >
      {{ tab.label }}
    </div>
  </div>

  <!-- 公告列表 -->
  <div v-loading="noticeLoading" class="notice-list" style="height: calc(100% - 40px); overflow-y: auto;">
    <transition-group name="fade">
      <div 
        v-for="notice in filteredNotices" 
        :key="notice.noticeId" 
        class="notice-item"
        :class="'notice-type-' + notice.type"
      >
        <el-tag 
          :type="typeStyle[notice.type]" 
          size="small"
          effect="plain"
          class="notice-tag"
        >
          {{ typeMap[notice.type] }}
        </el-tag>
        <div class="notice-content">
          <div class="text">{{ notice.content }}</div>
          <div class="time">
            <el-icon><Clock /></el-icon>
            {{ formatTime(notice.updatedAt) }}
          </div>
        </div>
      </div>
    </transition-group>

    <el-empty 
      v-if="!noticeLoading && filteredNotices.length === 0" 
      description="暂无相关公告"
      class="empty-notice"
    />
  </div>
</el-card>
</div>
    </header>

    <!-- 商品分类导航 -->
    <div class="category-nav">
      <button
        v-for="category in categories"
        :key="category"
        :class="{ active: currentCategory === category }"
        @click="changeCategory(category)"
      >
        {{ category }}
        <span v-if="category === '为你推荐'" class="hot-badge">HOT</span>
      </button>
    </div>

    <!-- 商品展示区 -->
    <section class="products">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else>
        <div class="product-grid">
          <div
            class="product-card"
            v-for="product in filteredProducts"
            :key="product.productId"
            @click="openProductDetail(product.productId)"
          >
            <div class="image-container">
              <img :src="'http://localhost:8092' + product.images" alt="Product Image" />
            </div>
            <div class="card-content">
              <h3 class="product-title">{{ product.productName }}</h3>
              <p class="product-description">{{ product.introduction }}</p>
              <div class="product-footer">
                <span class="product-price">¥{{ product.price }}</span>
                <div class="product-meta">
                  <span class="product-wants">{{ product.wants || 0 }}人想要</span>
                  <span class="product-clicks">
                    <el-icon><View /></el-icon>
                    {{ product.click || 0 }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="filteredProducts.length === 0" class="no-data">
          暂无商品数据
        </div>
      </div>
    </section>

    <!-- 页底 -->
    <MainFoots v-if="!isLoggedIn"></MainFoots>

    <!-- 右侧侧边栏 -->
    <RightSidebar  :userId="userId"/>
  </div>
</template>

<script>
import NavbarComponent from "@/components/components/NavbarComponent.vue";
import MainFoots from "@/components/components/MainFoots.vue";
import RightSidebar from '@/components/components/RightSidebar.vue'
import axios from "axios";
import{ElMessage,ElCarousel, ElCarouselItem} from 'element-plus'
import { 
  Plus, ChatLineRound, Iphone, Document, View,
  Mic, Notebook, DataBoard, Camera, EditPen,
  User, Football as FootballIcon, MagicStick, Reading 
} from "@element-plus/icons-vue";
import dayjs from 'dayjs'
export default {
  name: "Home",
  components: {
    ElCarousel,
    ElCarouselItem,
    NavbarComponent,
    MainFoots,
    Plus,
    ChatLineRound,
    RightSidebar,
    Iphone,
    Document,
    View,
    Mic, Notebook, DataBoard, Camera, EditPen,
    User, FootballIcon, MagicStick, Reading
  },
  data() {
    return {
      activeNoticeType: 0, // 0-全部 1-系统公告 2-活动通知 3-维护公告
    noticeTabs: [
      { type: 0, label: '全部公告' },
      { type: 1, label: '系统公告' },
      { type: 2, label: '活动通知' },
      { type: 3, label: '维护公告' }
    ],
    typeMap: {
      1: '系统公告',
      2: '活动通知',
      3: '维护公告'
    },
    typeStyle: {
      1: 'primary',
      2: 'success',
      3: 'warning'
    },
      bannerImages: [
        {
          image: require('@/assets/banner1.jpg'), // 本地图片示例
          title: '校园二手交易平台',
          description: '让闲置物品流动起来'
        },
        {
          image: require('@/assets/banner2.jpg'), // 网络图片示例
          title: '优质二手教材',
          description: '学长学姐的智慧传承',
          category: '二手教材'
        },
        {
          image:require('@/assets/banner3.jpg'),
          title: '数码产品专区',
          description: '高性价比电子设备',
          category: '数码'
        }
      ],
      products: [],
      topClickedProducts: [], // 新增点击量排行榜
      loading: false,
      isLoggedIn: false,
      userId:null,
      categories: ["为你推荐", "个人闲置", "吉他乐器", "摄影摄像", "钱币收藏"],
      currentCategory: "为你推荐",
      categoryMapping: {
        吉他乐器: ["乐器"],
        摄影摄像: ["数码"],
        钱币收藏: ["艺术品"],
        个人闲置: ["美妆", "书籍", "服饰", "家居", "运动户外", "文具", "玩具"],
      },
      sidebarCategories: [
        { name:'二手教材', category: '二手教材', icon: 'Reading' },
        { name: '乐器', category: '乐器', icon: 'Mic' },
        { name: '书籍', category: '书籍', icon: 'Notebook' },
        { name: '家居', category: '家居', icon: 'DataBoard' },
        { name: '数码', category: '数码', icon: 'Camera' },
        { name: '文具', category: '文具', icon: 'EditPen' },
        { name: '服饰', category: '服饰', icon: 'User' },
        { name: '玩具', category: '玩具', icon: 'FootballIcon' },
        { name: '美妆', category: '美妆', icon: 'MagicStick' },
        { name: '艺术品', category: '艺术品', icon: 'Reading' },
        { name: '运动户外', category: '运动户外', icon: 'FootballIcon' },
      ],
      notices: [],
      noticeLoading: false
    };
  },
  computed: {
    filteredNotices() {
    if (this.activeNoticeType === 0) return this.notices
    return this.notices.filter(n => n.type === this.activeNoticeType)
  },
    filteredProducts() {
      const products = Array.isArray(this.products) ? this.products : [];
      if (this.currentCategory === "为你推荐") {
        return this.topClickedProducts.slice(0, 10);
      }
      const targetCategories = this.categoryMapping[this.currentCategory] || [];
      return products.filter((product) => targetCategories.includes(product.category));
    }
  },
  // 在 Home 组件中添加 watch
watch: {
  userId(newVal) {
    console.log('userId 更新:', newVal)
  }
},
  mounted() {
    this.loadProducts();
    this.getUserDetails();
    this.loadNotices();
  },
  methods: {
    handleBannerClick(item) {
    if (item.category === '数码') {
      const routeData = this.$router.resolve({
        path: 'category',
        query: { category: '数码' }
      });
      window.open(routeData.href, '_blank');
    }
    else if (item.category === '二手教材') {
      const routeData = this.$router.resolve({
        path: 'category',
        query: { category: '二手教材' }
      });
      window.open(routeData.href, '_blank');
    }
  },
    async loadProducts() {
      this.loading = true;
      try {
        const response = await axios.get("http://localhost:8092/product/list");
        const productData = response.data?.data || response.data;
        // 处理点击量排行榜
        this.topClickedProducts = [...productData]
          .sort((a, b) => b.click - a.click)
          .slice(0, 10);
        console.log("ProductData:", productData)
        this.products = Array.isArray(productData) ? productData : [];
      } catch (error) {
        console.error("加载商品数据失败：", error);
        this.products = [];
      } finally {
        this.loading = false;
      }
    },
    async changeCategory(category) {
      this.currentCategory = category;
      if (category !== "为你推荐") {
        this.loading = true;
        try {
          const mappedCategories = this.categoryMapping[category] || [];
          const paramsCategory = mappedCategories.length > 0 ? mappedCategories : category;
          const response = await axios.get(
            `http://localhost:8092/product/byCategory?category=${paramsCategory}`
          );
          this.products = response.data.data;
        } catch (error) {
          console.error("加载分类商品失败:", error);
        } finally {
          this.loading = false;
        }
      }
    },
    async getUserDetails() {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      this.isLoggedIn = false;
      return;
    }

    const response = await axios.get('http://localhost:8092/user/getUserDetails', {
      headers: { Authorization: `Bearer ${token}` }
    });

    if (response.data.code === 200) {
      this.userInfo = response.data.data;
      this.isLoggedIn = this.userInfo.loginStatus === "1";
      this.userId = this.userInfo.userId;
    } else {
      console.error('获取用户详情失败:', response.data.msg);
      this.handleLogout();
    }
  } catch (error) {
    console.error('请求失败:', error);
    this.handleLogout();
  }
},
handleLogout() {
  localStorage.removeItem('token');
  this.isLoggedIn = false;
  ElMessage.error('登录状态已失效，请重新登录');
},
    handleCategoryClick(category) {
      const routeData = this.$router.resolve({
        path:'category',
        query: { category: category }
      });
      window.open(routeData.href, '_blank');  
    },
    openProductDetail(productId) {
      const routeData = this.$router.resolve({
        path: 'product',
        query: { productId: productId }
      });
      window.open(routeData.href, '_blank');
    },
    async loadNotices() {
      this.noticeLoading = true;
      try {
        const response = await axios.get('http://localhost:8092/notice/list');
        this.notices = response.data.data || [];
      } catch (error) {
        console.error('获取公告失败:', error);
      } finally {
        this.noticeLoading = false;
      }
    },
    formatTime(timeStr) {
      return dayjs(timeStr).format('YYYY-MM-DD HH:mm');
    },
  }
};
</script>

<style scoped>
/* 基础样式 */
#app {
  font-family: Arial, sans-serif;
  max-width: 1400px;
  margin: 0 auto;
}

/* 头部容器 */
.header {
  display: flex;
  align-items: flex-start;
  padding: 20px 15px;
  margin-bottom: 15px;
  min-height: auto;
}

/* 分类侧边栏 */
.category-sidebar {
  width: 160px;
  background: rgba(255,255,255,0.95);
  border-radius: 6px;
  padding: 10px;
  margin-right: 15px;
  box-shadow: 1px 1px 8px rgba(0,0,0,0.08);
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 10px;
  margin: 3px 0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #ffffff;
  border: 1px solid #eee;
  font-size: 13px;
}

.category-item:hover {
  background: #f8f9fa;
  transform: translateX(5px);
  box-shadow: 2px 2px 6px rgba(0,0,0,0.05);
}

/* 轮播图容器 */
.carousel-container {
  flex: 1;
  margin-left: 20px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 轮播图项 */
.carousel-item {
  position: relative;
  height: 400px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 轮播图文字 */
.carousel-caption {
  position: absolute;
  bottom: 40px;
  left: 40px;
  color: white;
  text-shadow: 1px 1px 4px rgba(0, 0, 0, 0.5);
  max-width: 600px;
}

.carousel-caption h2 {
  font-size: 2.5em;
  margin-bottom: 15px;
  color: #fff;
}

.carousel-caption p {
  font-size: 1.2em;
  line-height: 1.5;
}

/* 分类导航 */
.category-nav {
  display: flex;
  justify-content: center;
  margin: 25px 0;
  flex-wrap: wrap;
}

.category-nav button {
  position: relative;
  padding: 12px 25px;
  margin: 8px;
  border: none;
  border-radius: 25px;
  background-color: #f1c40f;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1.1em;
  font-weight: 500;
}

.hot-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #ff5500;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: bold;
}

.category-nav button:hover {
  background-color: #e0b91a;
  transform: translateY(-2px);
}

.category-nav button.active {
  background-color: #2ecc71;
  box-shadow: 0 2px 6px rgba(46, 204, 113, 0.4);
}

/* 商品展示区 */
.products {
  padding: 40px 20px;
}

.loading {
  text-align: center;
  font-size: 18px;
  color: #7f8c8d;
  padding: 40px 0;
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #95a5a6;
  font-size: 16px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 30px;
  padding: 20px;
}

.product-card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  overflow: hidden;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.image-container {
  width: 100%;
  height: 220px;
  overflow: hidden;
  position: relative;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover img {
  transform: scale(1.05);
}

.card-content {
  padding: 18px;
}

.product-title {
  font-size: 16px;
  color: #34495e;
  margin: 0 0 12px;
  font-weight: 600;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.product-description {
  font-size: 14px;
  color: #7f8c8d;
  line-height: 1.5;
  margin: 0 0 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  color: #ff5500;
  font-size: 18px;
  font-weight: bold;
}

.product-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-wants {
  color: #95a5a6;
  font-size: 13px;
}

.product-clicks {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #7f8c8d;
  font-size: 13px;
}

/* Element UI 轮播图样式覆盖 */
:deep(.el-carousel__arrow) {
  background-color: rgba(255, 255, 255, 0.3);
  color: #fff;
  transition: all 0.3s;
  width: 48px;
  height: 48px;
  font-size: 24px;
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(255, 255, 255, 0.7);
  color: #333;
}

:deep(.el-carousel__indicator) {
  padding: 12px 4px;
}

:deep(.el-carousel__button) {
  width: 28px;
  height: 4px;
  border-radius: 2px;
  background-color: rgba(255, 255, 255, 0.6);
  transition: all 0.3s;
}

:deep(.el-carousel__indicator.is-active .el-carousel__button) {
  background-color: #fff;
  width: 40px;
}

/* 公告板修复样式 */
.main-content {
  flex: 1;
  display: flex;
  gap: 20px;
}

.carousel-container {
  flex: 2;
}

.notice-board {
  flex: 1;
  min-width: 280px;
  height: 400px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  position: relative;
  overflow-y: auto;
  /* 防止内容抖动 */
  scrollbar-gutter: stable;
}

.notice-tabs {
  display: flex;
  gap: 20px;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
  background: #fff;
  z-index: 1;
  /* height: 40px; */
}

.tab-item {
  position: relative;
  padding: 12px 0;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
  font-weight: 500;
}

.tab-item:hover {
  color: #409EFF;
}

.tab-item.active {
  color: #409EFF;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background: #409EFF;
  border-radius: 1px;
}

.notice-list {
  /* 占据剩余高度 */
  flex: 1;
  /* 自动滚动 */
  overflow-y: auto;
  /* 滚动条占位 */
  scrollbar-gutter: stable;
  /* 简单间距调整 */
  padding-right: 8px;
}



.notice-list::-webkit-scrollbar {
  width: 8px; /* 加宽滚动条 */
  background-color: rgba(242, 242, 242, 0.5); /* 更明显的背景 */
}

.notice-list::-webkit-scrollbar-thumb {
  background: #f5f5f5;
  border-radius: 3px;
}

.notice-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.notice-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.notice-item {
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 4px;
  background: #f8f9fa;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.notice-item:hover {
  transform: translateX(3px);
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

.notice-type-1 { border-left-color: #409EFF; }
.notice-type-2 { border-left-color: #67C23A; }
.notice-type-3 { border-left-color: #E6A23C; }

.notice-content {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.time {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  display: flex;
  align-items: center;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
  }
  
  .notice-board {
    height: auto;
    min-height: 400px;
    margin-top: 20px;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    padding: 15px 10px;
  }

  .category-sidebar {
    display: none;
  }

  .carousel-container {
    margin-left: 0;
    height: 250px;
  }

  .notice-board {
    min-width: 100%;
  }

  .notice-tabs {
    gap: 12px;
    overflow-x: auto;
    padding: 0 15px;
  }

  .tab-item {
    flex-shrink: 0;
    padding: 8px 0;
  }
}

@media (max-width: 480px) {
  .carousel-container {
    height: 200px;
  }

  .carousel-item {
    height: 200px;
  }

  .product-grid {
    grid-template-columns: 1fr;
  }
}
</style>